package com.data.modules.ai.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.constant.WebsocketConst;
import com.data.modules.ai.entity.AiJs;
import com.data.modules.ai.mapper.AiJsMapper;
import com.data.modules.ai.service.IAiJsService;
import com.data.modules.log.entity.AICommand;
import com.data.modules.log.entity.AIDTO;
import com.data.modules.message.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Objects;

/**
 * @Description: ai_js 脚本表
 * @Author: data-boot
 * @Date: 2022-04-15
 * @Version: V1.0
 */
@Slf4j
@Service
public class AiJsServiceImpl extends ServiceImpl<AiJsMapper, AiJs> implements IAiJsService {

    @Autowired
    private WebSocket webSocket;

    @Override
    public void pubScriptToClient(AiJs aiJs) throws Exception {
        String[] userIds = aiJs.getCreateBy().split(",");
        for (String userId : userIds) {
            AIDTO dto = new AIDTO();
            dto.setCommand(aiJs.getStatus());
            String script = aiJs.getJsScript();
            dto.setScript(script);
            dto.setId(aiJs.getId());
            dto.setName(aiJs.getJsName());

            AICommand command = new AICommand();
            command.setData(dto);
            command.setType(WebsocketConst.AI_COMMAND);

            // 判断userId 是否在线
            Session session = WebSocket.sessionPool.get(userId);
            if (session == null || !session.isOpen()) {
                log.error(userId + " WsLogServiceImpl send Error session is down");
            }
            String msg = JSON.toJSONString(command);
            log.info("===pubScript userId:{},msg:{}", userId, msg);
            webSocket.sendMessage(userId, msg);

        }

        if (Objects.equals(WebsocketConst.AI_RERUN, aiJs.getStatus())) {
            this.lambdaUpdate().set(AiJs::getStatus,1).eq(AiJs::getId,aiJs.getId()).update();
        }
        if (Objects.equals(WebsocketConst.AI_STOP, aiJs.getStatus()) ||
                Objects.equals(WebsocketConst.AI_STOPALL, aiJs.getStatus())) {
            this.lambdaUpdate().set(AiJs::getStatus,0).eq(AiJs::getId,aiJs.getId()).update();
        }

    }
}
